package cn.gene.timeyan.ums.webapi.ums.service.impl;

import cn.gene.timeyan.article.service.ArticleService;
import cn.gene.timeyan.common.constant.RedisConstants;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.restful.ResponseCode;
import cn.gene.timeyan.common.utils.FormUtils;
import cn.gene.timeyan.coo.service.CooperationService;
import cn.gene.timeyan.pojo.article.model.Article;
import cn.gene.timeyan.pojo.coo.dto.CooperationDeleteDTO;
import cn.gene.timeyan.pojo.coo.model.Cooperation;
import cn.gene.timeyan.pojo.ums.model.BrowsingHistory;
import cn.gene.timeyan.pojo.ums.vo.BrowsingHistoryArticleVO;
import cn.gene.timeyan.pojo.ums.vo.BrowsingHistoryHelpVO;
import cn.gene.timeyan.pojo.ums.vo.BrowsingHistoryVO;
import cn.gene.timeyan.pojo.ums.vo.UserSimpleVO;
import cn.gene.timeyan.ums.service.IBrowsingHistoryService;
import cn.gene.timeyan.ums.webapi.ums.mapper.BrowsingHistoryMapper;
import cn.gene.timeyan.ums.webapi.ums.mapper.UserDetailMapper;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 浏览记录      服务实现类*
 *
 * @author LWG
 * @date 2022/7/22 17:41
 * @since 1.0.0@gene.cn
 */
@Service
@DubboService
public class BrowsingHistoryServiceImpl implements IBrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;
    @Autowired
    private UserDetailMapper userDetailMapper;
    @DubboReference
    private ArticleService dubboArticleService;
    @DubboReference
    private CooperationService dubboCooperationService;
    @Resource(name = "redisTemplate2")
    private RedisTemplate redisTemplate;
    private static final Integer PEAGESIZE=20;

    /**
     * 获取浏览记录列表
     * @param userId
     * @param page
     * @return
     */
    @Override
    public List<BrowsingHistoryVO> browsingHistoryList(Long userId,Integer page) {
        String key= RedisConstants.BROWSING_HISTORY+userId;
        //判断是否有缓存
        List<BrowsingHistoryVO> result=new ArrayList<>();
        if (redisTemplate.hasKey(key)&&redisTemplate.opsForZSet().size(key)>=page*PEAGESIZE){
            //有缓存,且足够
            Set<String> list=redisTemplate.opsForZSet().reverseRange(key,(page-1)*PEAGESIZE,page*PEAGESIZE-1);
            for (String id: list) {
                if (id.contains(":0")){
                    result.add(JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(), BrowsingHistoryArticleVO.class));
                }else{
                    result.add(JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(), BrowsingHistoryHelpVO.class));
                }
            }
            if (result.size()==0){
                throw new TimeyanServiceException(ResponseCode.NOT_FOUND,"未找到记录");
            }
            return result;
        }else if (redisTemplate.opsForZSet().size(key)<page*PEAGESIZE){
            //有缓存，且不够
//            PageHelper.startPage(page,PEAGESIZE);
            List<BrowsingHistory> browsingHistory=browsingHistoryMapper.historyByUserId(userId);
            for (BrowsingHistory history:browsingHistory) {
                double time= FormUtils.parseTimeByLocalDateTime(history.getViewTime());
                //存入缓存
                if ("0".equals(history.getModuleType())){
                    redisTemplate.opsForZSet().add(key,history.getViewId()+":0",time);
                    BrowsingHistoryArticleVO articleVO=toBrowsingHistoryArticleVO(history,key);
                    Map<String,Object> map=new HashMap<>();
                    map.put(history.getViewId()+":0",JSON.toJSON(articleVO));
                    redisTemplate.opsForHash().putAll(key+"detail",map);
                }else{
                    redisTemplate.opsForZSet().add(key,history.getViewId()+":1",time);
                    BrowsingHistoryHelpVO helpVO=toBrowsingHistoryHelpVO(history,key);
                    Map<String,Object> map=new HashMap<>();
                    map.put(history.getViewId()+":1",JSON.toJSON(helpVO));
                    redisTemplate.opsForHash().putAll(key+"detail",map);
                }
            }
            Set<String> list=redisTemplate.opsForZSet().reverseRange(key,(page-1)*PEAGESIZE,page*PEAGESIZE-1);
            for (String id: list) {
                if (id.contains(":0")){
                    result.add(JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(), BrowsingHistoryArticleVO.class));
                }else{
                    result.add(JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(), BrowsingHistoryHelpVO.class));
                }
            }
            if (result.size()==0){
                throw new TimeyanServiceException(ResponseCode.NOT_FOUND,"未找到记录");
            }
            return result;
        }else{
            //没缓存
//            PageHelper.startPage(1,page*PEAGESIZE);
            List<BrowsingHistory> browsingHistory=browsingHistoryMapper.historyByUserId(userId);
            for (BrowsingHistory history:browsingHistory) {
                System.out.println(browsingHistory);
                double time= FormUtils.parseTimeByLocalDateTime(history.getViewTime());
                //存入缓存
                if ("0".equals(history.getModuleType())){
                    BrowsingHistoryArticleVO articleVO=toBrowsingHistoryArticleVO(history,key);
                    Map<String,Object> map=new HashMap<>();
                    map.put(history.getViewId()+":0",JSON.toJSON(articleVO));
                    redisTemplate.opsForHash().putAll(key+"detail",map);
                }else{
                    redisTemplate.opsForZSet().add(key,history.getViewId()+":1",time);
                    BrowsingHistoryHelpVO helpVO=toBrowsingHistoryHelpVO(history,key);
                    Map<String, Object> map = new HashMap<>();
                    map.put(history.getViewId() + ":1", JSON.toJSON(helpVO));
                    redisTemplate.opsForHash().putAll(key + "detail", map);
                }
            }
            Set<String> list=redisTemplate.opsForZSet().reverseRange(key,0,page*PEAGESIZE-1);
            for (String id: list) {
                if (id.contains(":0")){
                    result.add(JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(), BrowsingHistoryArticleVO.class));
                }else{
                    result.add(JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(), BrowsingHistoryHelpVO.class));
                }
            }
            if (result.size()==0){
                throw new TimeyanServiceException(ResponseCode.NOT_FOUND,"未找到记录");
            }
            return result;
        }
    }

    /**
     * 删除某一条历史记录
     * @param cooperationDeleteDTO
     */
    @Override
    public void deleteBrowsingHistory(CooperationDeleteDTO cooperationDeleteDTO) {
        String key= RedisConstants.BROWSING_HISTORY+cooperationDeleteDTO.getUserId();
        String id=cooperationDeleteDTO.getViewId()+":"+cooperationDeleteDTO.getType();
        //判断是否存在缓存
        System.out.println(redisTemplate.hasKey(key));
        System.out.println(key);
        if (redisTemplate.hasKey(key)){
            System.out.println(redisTemplate.opsForHash().get(key+"detail",id+":"+cooperationDeleteDTO.getType()));
            //有缓存,清除缓存
            System.out.println(redisTemplate.opsForZSet().remove(key,id+":"+cooperationDeleteDTO.getType()));;
            System.out.println(redisTemplate.opsForHash().delete(key+"detail",id+":"+cooperationDeleteDTO.getType()));
        }
        //删除数据库
        int rows=browsingHistoryMapper.deleteByViewId(cooperationDeleteDTO.getViewId());
        if (rows<1){
            throw new TimeyanServiceException(ResponseCode.ERR_DELETE,"删除失败，请稍后再进行此操作");
        }
    }

    /**
     * 添加一条浏览记录
     * @param browsingHistory
     */
    @Override
    public void addBrowsingHistory(BrowsingHistory browsingHistory) {
        int rows=browsingHistoryMapper.addBrowsingHistory(browsingHistory);
    }

    /**
     * 转换为BrowsingHistoryArticleVO
     * @param history
     * @param key
     * @return
     */
    public BrowsingHistoryArticleVO toBrowsingHistoryArticleVO(BrowsingHistory history,String key){
        BrowsingHistoryArticleVO articleVO=new BrowsingHistoryArticleVO();
        articleVO.setBrowsingTime(history.getViewTime());
        //获取文章信息
        Article article=dubboArticleService.getAricleByAricleId(history.getSourceId());
        if (article!=null) {
            articleVO.setType("0");
            articleVO.setTitle(article.getArticleTitle());
            if (article.getArticleContent().length() > 50) {
                articleVO.setContent(article.getArticleContent().substring(0, 50) + "...");
            } else {
                articleVO.setContent(article.getArticleContent());
            }
            articleVO.setUrl("/article" + history.getSourceId());
            articleVO.setCollection(article.getArticleCollection());
            articleVO.setComment(article.getArticleComment());
            articleVO.setLike(article.getArticleLike());
            //获取作者信息
            UserSimpleVO user = userDetailMapper.selectUserCommentVOByUserId(article.getUserId());
            articleVO.setNickName(user.getNickname());
            articleVO.setAvatar(user.getAvatar());
            articleVO.setIntroduction(user.getIntroduction());
        }else{
            articleVO.setMessage("帖子已删除");
        }
        return articleVO;
    }
    /**
     * 转换为BrowsingHistoryHelpVO
     * @param history
     * @param key
     * @return
     */
    public BrowsingHistoryHelpVO toBrowsingHistoryHelpVO(BrowsingHistory history,String key){
        BrowsingHistoryHelpVO helpVO=new BrowsingHistoryHelpVO();
        helpVO.setBrowsingTime(history.getViewTime());
        //获取互助信息
        Cooperation cooperation=dubboCooperationService.getHelpByHelpId(history.getSourceId());
        if (cooperation!=null){
        helpVO.setType("1");
        helpVO.setTitle(cooperation.getHelpTitle());
        if (cooperation.getHelpContent().length()>50){
            helpVO.setContent(helpVO.getContent().substring(0,50)+"...");
        }else{
            helpVO.setContent(helpVO.getContent());
        }
        helpVO.setUrl("/help"+history.getSourceId());
        helpVO.setDifficulty(cooperation.getDifficulty());
        helpVO.setApplyType(cooperation.getApplyType());
        helpVO.setState(cooperation.getHelpState());
        helpVO.setReward(cooperation.getRewardValue());
        helpVO.setRewardType(cooperation.getRewardType());
        helpVO.setStartTime(cooperation.getStartTime());
        helpVO.setEndTime(cooperation.getEndTime());
        helpVO.setAddress(cooperation.getAddress());
        //获取用户信息
        UserSimpleVO user=userDetailMapper.selectUserCommentVOByUserId(cooperation.getUserId());
        helpVO.setNickName(user.getNickname());
        helpVO.setAvatar(user.getAvatar());
        helpVO.setIntroduction(user.getIntroduction());
        }
        helpVO.setMessage("互助已被删除");
        return helpVO;
    }

}
